package com.diit.analysisitest;

import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.JsonReader;
import android.util.JsonWriter;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.diit.analysisitest.slidinglayer.SlidingLayer;
import com.esri.android.map.*;
import com.esri.android.map.ags.ArcGISLocalTiledLayer;
import com.esri.android.map.event.OnLongPressListener;
import com.esri.android.map.event.OnSingleTapListener;
import com.esri.core.geodatabase.Geodatabase;
import com.esri.core.geodatabase.GeodatabaseFeatureTable;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Geometry;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Line;
import com.esri.core.geometry.MultiPath;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.geometry.Polyline;
import com.esri.core.geometry.SpatialReference;
import com.esri.core.map.CallbackListener;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.map.Graphic;
import com.esri.core.symbol.FillSymbol;
import com.esri.core.symbol.MarkerSymbol;
import com.esri.core.symbol.SimpleFillSymbol;
import com.esri.core.symbol.SimpleLineSymbol;
import com.esri.core.symbol.SimpleMarkerSymbol;
import com.esri.core.table.FeatureTable;
import com.esri.core.table.TableException;
import com.esri.core.tasks.query.QueryParameters;
import com.google.gson.Gson;

import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.util.JSONPObject;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;

import lecho.lib.hellocharts.listener.PieChartOnValueSelectListener;
import lecho.lib.hellocharts.model.PieChartData;
import lecho.lib.hellocharts.model.SliceValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.PieChartView;

public class MainActivity extends AppCompatActivity {
    private MapView mMapView;

    private final static int ANALYSIS = 1;
    private FeatureLayer dataFeatureLayer;
    private ArrayList<Point> mPoints; // 存放所采点的集合
    private GraphicsLayer messureLayer;// 定义测距测面的要素图层
    private Polygon messurePolygon;// 定义一个面
    private Polyline messurePolyline;// 定义测距线的组合
    private Line messureLine;// 定义测距线段
    private Graphic messureAreaGraphic = null;// 定义面的要素
    private Graphic messureLineGraphic = null;// 定义线的要素
    private MarkerSymbol mMarkerSymbol; // 采点标记的样式
    private SimpleLineSymbol messureLineSymbol;// 定义测距测面线的样式
    private SimpleMarkerSymbol messureMarkerSymbol;// 定义测距测面点的样式
    private FillSymbol messureFillSymbol;// 定义测面的显示样式
    private SimpleLineSymbol pAnalysistSymbol;//图斑边线样式
    private List<Graphic> pointAnalysistGraphics;//分析图斑图形集合
    private GraphicsLayer pointAnalysistAllGraphicsLayer;//
    private GraphicsLayer pointAnalysistOneGraphicsLayer;
    private FillSymbol messureFillSymbol_red;//红色面样式
    private FillSymbol messureFillSymbol_blue;//蓝色面样式
    private FillSymbol messureFillSymbol_green;//绿色面样式

    private LandUseStatusAnalysisResult Landresult;
    private List<PAnalysistItemInfo> pAnalysistItemInfoList;
    private SlidingLayer mySlidingLayer;

    private LinearLayout cvTjResult;
    private TextView tv_zmj;
    private TextView tv_nmj;
    private TextView tv_jmj;
    private TextView tv_wmj;
    private TextView tv_controltitle;
    private ListView lv;
    private LinearLayout ll_zj1;
    private LinearLayout ll_zj2;
    private RadioButton rbtSummaryInfo;
    private RadioButton rbtMoreInfo;
    private RadioButton rbt_xzqh;
    private RadioButton rbt_ydlx;
    private RadioButton rbt_dlmc;
    private TongJiFenXiAdapter tjadapter;
    private ArrayList<Point> ptList;
    private TableLayout tbMoreInfo;
    private TextView tvdlmc;
    private TextView tvdllb;
    private TextView tbPlanInfoTitle;
    private TableLayout tbPlanInfo;
    private Map<String, List<Graphic>> LandPer = null;
    private PieChartView chartTjResult;
    private TextView tbSummaryTitle;
    private TableLayout tbSummary;
    private TextView tbMoreInfoTitle;
    private TextView tbControlTitle2;
    private TableLayout tbControl2;
    private TextView tbControlTitle;
    private TableLayout tbControl;
    private TextView tvFarmLandSum;
    private TextView tvBuildLandSum;
    private TextView tvNoUseLandSum;
    private TextView tvFarmLandArea;
    private TextView tvBuildLandArea;
    private TextView tvNoUseLandArea;
    private TextView tv_sum;
    private TextView tv_area;

    private static final ExecutorService DEFAULT_TASK_EXECUTOR;

    private static ExecutorService LIMITED_TASK_EXECUTOR = null;

    static {
        LIMITED_TASK_EXECUTOR = (ExecutorService) Executors
                .newFixedThreadPool(5);
        DEFAULT_TASK_EXECUTOR = LIMITED_TASK_EXECUTOR;
    }



    public Handler handler = new Handler() {
        private Object removeBasemap;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == ANALYSIS) {
                if (Landresult.getTotalArea() < 0.01) {
                    Toast.makeText(MainActivity.this, "范围内没有数据", Toast.LENGTH_SHORT).show();
                    mySlidingLayer.closeLayer(true);// 关闭综合查询侧滑
                } else {
                    mySlidingLayer.openLayer(true);
                    cvTjResult.setVisibility(View.GONE);
                    tv_controltitle.setVisibility(View.GONE);
                    lv.setVisibility(View.VISIBLE);
                    ll_zj2.setVisibility(View.VISIBLE);
                    rbt_xzqh.setVisibility(View.GONE);
                    rbt_dlmc.setVisibility(View.GONE);
                    rbt_ydlx.setVisibility(View.GONE);
                    rbtSummaryInfo.setVisibility(View.VISIBLE);
                    rbtMoreInfo.setVisibility(View.VISIBLE);
                    String q = String.valueOf(Landresult.getTotalArea());
                    NumberFormat nf = NumberFormat.getNumberInstance();
                    nf.setMaximumFractionDigits(2);
                    Double d = Double.parseDouble(q);
                    String b = nf.format(d);
                    b = b + "亩,其中:";
                    tv_zmj.setText(b);

                    String f = SafeConvertUtil.DoubleToString(Landresult.getFarmArea(), 2);
                    f = f + "亩";
                    String j = SafeConvertUtil.DoubleToString(Landresult.getBuildArea(), 2);
                    j = j + "亩";
                    String w = SafeConvertUtil.DoubleToString(Landresult.getNoUseArea(), 2);
                    w = w + "亩";
                    tv_nmj.setText(f);
                    tv_jmj.setText(j);
                    tv_wmj.setText(w);

                    List<LusarBean> lusarList = new ArrayList<LusarBean>();
                    for (int i = 0; i < Landresult.getResultList().size(); i++) {
                        LusarBean bean = new LusarBean();
                        bean.setXzqh(Landresult.getResultList().get(i).getAdmName());
                        bean.setNong(SafeConvertUtil
                                .DoubleToString(Landresult.getResultList().get(i).getFarmLand().getTotalArea(), 2));
                        bean.setJian(SafeConvertUtil
                                .DoubleToString(Landresult.getResultList().get(i).getBuildLand().getTotalArea(), 2));
                        bean.setWei(SafeConvertUtil
                                .DoubleToString(Landresult.getResultList().get(i).getNoUseLand().getTotalArea(), 2));
                        lusarList.add(bean);
                    }
                    ;
                    tjadapter = new TongJiFenXiAdapter(MainActivity.this, lusarList);
                    // tjadapter = new TongJiFenXiAdapter(MapViewActivity.this,
                    // pAnalysistItemInfoList);
                    lv.setAdapter(tjadapter);
                    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            pointAnalysistOneGraphicsLayer.removeAll();
                            ptList = new ArrayList<>();
                            for (Graphic graphic : Landresult.getResultList().get(position).GraphicList) {

                                MultiPath pg = (MultiPath) graphic.getGeometry();
                                int pathSize = pg.getPathCount();

                                for (int j = 0; j < pathSize; j++) {
                                    int size = pg.getPathSize(j);
                                    for (int i = 0; i < size; i++) {
                                        Point pt = pg.getPoint(i);
                                        ptList.add(pt);
                                    }
                                }
                                pointAnalysistOneGraphicsLayer.addGraphic(graphic);
                            }
                            zoomToArea(ptList);
                        }
                    });
                    GenerateStatusSummaryDataByArea(Landresult);
                    InitLandTypeExcel(Landresult);
                    InitClassName(Landresult);
                    rbt_xzqh.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            GenerateStatusSummaryDataByArea(Landresult);
                        }
                    });
                    rbt_ydlx.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            GenerateStatusSummaryDataByLandType();
                        }
                    });
                    rbt_dlmc.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            GenerateStatusSummaryDataByClassName(Landresult);
                        }
                    });

                }
            }
        }

        private void InitClassName(LandUseStatusAnalysisResult landresultResult) {
            // TODO Auto-generated method stub
            LandUseStatusItem item = getLandUseStatusItemByClassName(landresultResult);
            tbMoreInfo.removeViews(1, tbMoreInfo.getChildCount() - 1);
            tvdlmc.setText("地类名称");
            tvdllb.setText("地类类别");

            // 农用地汇总
            for (Map.Entry<String, LandType> entry : item.FarmLand.LandTypeMap.entrySet()) {
                String key = entry.getKey();
                LandType landType = entry.getValue();
                if (key != null && !key.isEmpty()) {
                    TableRow tbRowTemp = new TableRow(MainActivity.this);
                    TextView tvTypeTemp = new TextView(MainActivity.this);
                    tvTypeTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvTypeTemp.setPadding(5, 5, 5, 5);
                    TextView tvNameTemp = new TextView(MainActivity.this);
                    tvNameTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvNameTemp.setPadding(5, 5, 5, 5);
                    TextView tvSumTemp = new TextView(MainActivity.this);
                    tvSumTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvSumTemp.setPadding(5, 5, 5, 5);
                    TextView tvAreaTemp = new TextView(MainActivity.this);
                    tvAreaTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvAreaTemp.setPadding(5, 5, 5, 5);

                    tvNameTemp.setText(landType.LandTypeName);
                    tvTypeTemp.setText("农用地");
                    tvSumTemp.setText(landType.TotalNums.toString());
                    tvAreaTemp.setText(String.format("%.2f", landType.TotalAreas));

                    tbRowTemp.addView(tvNameTemp);
                    tbRowTemp.addView(tvTypeTemp);
                    tbRowTemp.addView(tvSumTemp);
                    tbRowTemp.addView(tvAreaTemp);

                    tbMoreInfo.addView(tbRowTemp);
                }
            }
            // 建设用地汇总
            for (Map.Entry<String, LandType> entry : item.BuildLand.LandTypeMap.entrySet()) {
                String key = entry.getKey();
                LandType landType = entry.getValue();
                if (key != null && !key.isEmpty()) {
                    TableRow tbRowTemp = new TableRow(MainActivity.this);
                    TextView tvTypeTemp = new TextView(MainActivity.this);
                    tvTypeTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvTypeTemp.setPadding(5, 5, 5, 5);
                    TextView tvNameTemp = new TextView(MainActivity.this);
                    tvNameTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvNameTemp.setPadding(5, 5, 5, 5);
                    TextView tvSumTemp = new TextView(MainActivity.this);
                    tvSumTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvSumTemp.setPadding(5, 5, 5, 5);
                    TextView tvAreaTemp = new TextView(MainActivity.this);
                    tvAreaTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvAreaTemp.setPadding(5, 5, 5, 5);

                    tvNameTemp.setText(landType.LandTypeName);
                    tvTypeTemp.setText("建设用地");
                    tvSumTemp.setText(landType.TotalNums.toString());
                    tvAreaTemp.setText(String.format("%.2f", landType.TotalAreas));

                    tbRowTemp.addView(tvNameTemp);
                    tbRowTemp.addView(tvTypeTemp);
                    tbRowTemp.addView(tvSumTemp);
                    tbRowTemp.addView(tvAreaTemp);
                    tbMoreInfo.addView(tbRowTemp);
                }
            }
            // 未利用地汇总
            for (Map.Entry<String, LandType> entry : item.NoUseLand.LandTypeMap.entrySet()) {
                String key = entry.getKey();
                LandType landType = entry.getValue();
                if (key != null && !key.isEmpty()) {
                    TableRow tbRowTemp = new TableRow(MainActivity.this);
                    TextView tvTypeTemp = new TextView(MainActivity.this);
                    tvTypeTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvTypeTemp.setPadding(5, 5, 5, 5);
                    TextView tvNameTemp = new TextView(MainActivity.this);
                    tvNameTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvNameTemp.setPadding(5, 5, 5, 5);
                    TextView tvSumTemp = new TextView(MainActivity.this);
                    tvSumTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvSumTemp.setPadding(5, 5, 5, 5);
                    TextView tvAreaTemp = new TextView(MainActivity.this);
                    tvAreaTemp.setBackgroundResource(R.drawable.table_frame_gray);
                    tvAreaTemp.setPadding(5, 5, 5, 5);

                    tvNameTemp.setText(landType.LandTypeName);
                    tvTypeTemp.setText("未利用地");
                    tvSumTemp.setText(landType.TotalNums.toString());
                    tvAreaTemp.setText(String.format("%.2f", landType.TotalAreas));

                    tbRowTemp.addView(tvNameTemp);
                    tbRowTemp.addView(tvTypeTemp);
                    tbRowTemp.addView(tvSumTemp);
                    tbRowTemp.addView(tvAreaTemp);
                    tbMoreInfo.addView(tbRowTemp);
                }
            }

            // 合计
            TableRow tbRowTemp = new TableRow(MainActivity.this);
            TextView tvTypeTemp = new TextView(MainActivity.this);
            tvTypeTemp.setBackgroundResource(R.drawable.table_frame_gray);
            tvTypeTemp.setPadding(5, 5, 5, 5);
            TextView tvNameTemp = new TextView(MainActivity.this);
            tvNameTemp.setBackgroundResource(R.drawable.table_frame_gray);
            tvNameTemp.setPadding(5, 5, 5, 5);
            TextView tvSumTemp = new TextView(MainActivity.this);
            tvSumTemp.setBackgroundResource(R.drawable.table_frame_gray);
            tvSumTemp.setPadding(5, 5, 5, 5);
            TextView tvAreaTemp = new TextView(MainActivity.this);
            tvAreaTemp.setBackgroundResource(R.drawable.table_frame_gray);
            tvAreaTemp.setPadding(5, 5, 5, 5);

            int nums = item.FarmLand.TotalNums + item.BuildLand.TotalNums + item.NoUseLand.TotalNums;
            double areas = item.FarmLand.TotalArea + item.BuildLand.TotalArea + item.NoUseLand.TotalArea;

            tvNameTemp.setText("合计");
            tvTypeTemp.setText("");
            tvSumTemp.setText(String.valueOf(nums));
            tvAreaTemp.setText(String.format("%.2f", areas));

            tbRowTemp.addView(tvNameTemp);
            tbRowTemp.addView(tvTypeTemp);
            tbRowTemp.addView(tvSumTemp);
            tbRowTemp.addView(tvAreaTemp);
            tbMoreInfo.addView(tbRowTemp);
            // 隐藏规划数据展示表格
            tbPlanInfoTitle.setVisibility(View.GONE);
            tbPlanInfo.setVisibility(View.GONE);

        }

        private void GenerateStatusSummaryDataByArea(LandUseStatusAnalysisResult landStatusResult) {

            Double sumArea = landStatusResult.getTotalArea();

            PieChartData data;
            Map<String, List<Graphic>> percentMap = new HashMap<>();

            List<SliceValue> values = new ArrayList<SliceValue>();
            for (int i = 0; i < landStatusResult.getResultList().size(); ++i) {
                LandUseStatusItem landUseStatusItemTemp = landStatusResult.getResultList().get(i);
                Double totalArea = (landUseStatusItemTemp.getFarmLand().getTotalArea()
                        + landUseStatusItemTemp.getBuildLand().getTotalArea()
                        + landUseStatusItemTemp.getNoUseLand().getTotalArea());
                if (totalArea > 0) {
                    Double valueTemp = totalArea * 100 / sumArea;
                    valueTemp = Double.valueOf(SafeConvertUtil.DoubleToString(valueTemp, 2));
                    SliceValue sliceValue = new SliceValue(valueTemp.floatValue(), ChartUtils.nextColor());
                    sliceValue.setLabel(landUseStatusItemTemp.getAdmName() + ":"
                            + SafeConvertUtil.DoubleToString(totalArea, 2) + "亩");
                    percentMap.put(landUseStatusItemTemp.getAdmName() + ":"
                            + SafeConvertUtil.DoubleToString(totalArea, 2) + "亩", landUseStatusItemTemp.GraphicList);
                    values.add(sliceValue);
                }
            }

            data = new PieChartData(values);

            data.setHasLabels(true);
            data.setHasLabelsOnlyForSelected(false);
            // data.setHasLabelsOutside(true);

            LandPer = percentMap;
            chartTjResult.setPieChartData(data);

            // 显示现状数据表格
            tbSummaryTitle.setVisibility(View.VISIBLE);
            tbSummary.setVisibility(View.VISIBLE);
            tbMoreInfoTitle.setVisibility(View.VISIBLE);
            tbMoreInfo.setVisibility(View.VISIBLE);
            // 隐藏规划数据表格

            tbControlTitle.setVisibility(View.GONE);
            tbControl.setVisibility(View.GONE);
            tbControlTitle2.setVisibility(View.GONE);
            tbControl2.setVisibility(View.GONE);
            tbPlanInfoTitle.setVisibility(View.GONE);
            tbPlanInfo.setVisibility(View.GONE);

            // chartItemInfo.setText("");
        }

        private void GenerateStatusSummaryDataByLandType() {
            PieChartData data;
            List<SliceValue> values = new ArrayList<SliceValue>();
            Map<String, List<Graphic>> percentMap = new HashMap<>();
            String q = String.format("%.2f", Landresult.getFarmArea());
            Double f = Double.parseDouble(q);
            SliceValue sliceValuef = new SliceValue(f.floatValue(), ChartUtils.COLOR_GREEN);
            sliceValuef.setLabel("农用地:" + f + "亩");
            percentMap.put("农用地:" + f + "亩", Landresult.FarmGraphic);
            values.add(sliceValuef);
            String q1 = String.format("%.2f", Landresult.getBuildArea());
            Double j = Double.parseDouble(q1);
            SliceValue sliceValuej = new SliceValue(j.floatValue(), ChartUtils.COLOR_RED);
            sliceValuej.setLabel("建设用地:" + j + "亩");
            percentMap.put("建设用地:" + j + "亩", Landresult.BuildGraphic);
            values.add(sliceValuej);
            String q2 = String.format("%.2f", Landresult.getNoUseArea());
            Double w = Double.parseDouble(q2);
            SliceValue sliceValuew = new SliceValue(w.floatValue(), ChartUtils.COLOR_BLUE);
            sliceValuew.setLabel("未使用地:" + w + "亩");
            percentMap.put("未使用地:" + w + "亩", Landresult.NoUseGraphic);
            values.add(sliceValuew);
            data = new PieChartData(values);
            LandPer = percentMap;

            data.setHasLabels(true);
            data.setHasLabelsOnlyForSelected(false);
            chartTjResult.setPieChartData(data);

        }

        private void GenerateStatusSummaryDataByClassName(LandUseStatusAnalysisResult landStatusResult) {
            // TODO Auto-generated method stub
            LandUseStatusItem item = getLandUseStatusItemByClassName(landStatusResult);
            Double sumArea = item.FarmLand.TotalArea + item.BuildLand.TotalArea + item.NoUseLand.TotalArea;
            PieChartData data;
            Map<String, List<Graphic>> percentMap = new HashMap<>();

            List<SliceValue> values = new ArrayList<SliceValue>();
            for (Map.Entry<String, LandType> entry : item.FarmLand.LandTypeMap.entrySet()) {
                String key = entry.getKey();
                LandType landType = entry.getValue();
                if (key != null && !key.isEmpty()) {
                    Double valueTemp = landType.TotalAreas * 100 / sumArea;
                    valueTemp = Double.valueOf(SafeConvertUtil.DoubleToString(valueTemp, 2));
                    SliceValue sliceValue = new SliceValue(valueTemp.floatValue(), ChartUtils.COLOR_GREEN);
                    sliceValue.setLabel(
                            landType.LandTypeName + ":" + SafeConvertUtil.DoubleToString(landType.TotalAreas, 2) + "亩");
                    percentMap.put(
                            landType.LandTypeName + ":" + SafeConvertUtil.DoubleToString(landType.TotalAreas, 2) + "亩",
                            landType.Graphic);
                    values.add(sliceValue);
                }
            }
            for (Map.Entry<String, LandType> entry : item.BuildLand.LandTypeMap.entrySet()) {
                String key = entry.getKey();
                LandType landType = entry.getValue();
                if (key != null && !key.isEmpty()) {
                    Double valueTemp = landType.TotalAreas * 100 / sumArea;
                    valueTemp = Double.valueOf(SafeConvertUtil.DoubleToString(valueTemp, 2));
                    SliceValue sliceValue = new SliceValue(valueTemp.floatValue(), ChartUtils.COLOR_RED);
                    sliceValue.setLabel(
                            landType.LandTypeName + ":" + SafeConvertUtil.DoubleToString(landType.TotalAreas, 2) + "亩");
                    percentMap.put(
                            landType.LandTypeName + ":" + SafeConvertUtil.DoubleToString(landType.TotalAreas, 2) + "亩",
                            landType.Graphic);
                    values.add(sliceValue);
                }
            }
            for (Map.Entry<String, LandType> entry : item.NoUseLand.LandTypeMap.entrySet()) {
                String key = entry.getKey();
                LandType landType = entry.getValue();
                if (key != null && !key.isEmpty()) {
                    Double valueTemp = landType.TotalAreas * 100 / sumArea;
                    valueTemp = Double.valueOf(SafeConvertUtil.DoubleToString(valueTemp, 2));
                    SliceValue sliceValue = new SliceValue(valueTemp.floatValue(), ChartUtils.COLOR_BLUE);
                    sliceValue.setLabel(
                            landType.LandTypeName + ":" + SafeConvertUtil.DoubleToString(landType.TotalAreas, 2) + "亩");
                    percentMap.put(
                            landType.LandTypeName + ":" + SafeConvertUtil.DoubleToString(landType.TotalAreas, 2) + "亩",
                            landType.Graphic);
                    values.add(sliceValue);
                }
            }

            LandPer = percentMap;
            data = new PieChartData(values);
            data.setHasLabels(true);
            data.setHasLabelsOnlyForSelected(false);
            // data.setHasLabelsOutside(true);

            chartTjResult.setPieChartData(data);

        }

        private LandUseStatusItem getLandUseStatusItemByClassName(LandUseStatusAnalysisResult landresultResult) {
            // TODO Auto-generated method stub
            LandUseStatusItem item = new LandUseStatusItem();
            item.FarmLand = new FarmLand();
            item.FarmLand.TotalNums = 0;
            item.FarmLand.TotalArea = 0.0;
            item.FarmLand.LandTypeMap = new HashMap<>();
            item.BuildLand = new BuildLand();
            item.BuildLand.TotalNums = 0;
            item.BuildLand.TotalArea = 0.0;
            item.BuildLand.LandTypeMap = new HashMap<>();
            item.NoUseLand = new NoUseLand();
            item.NoUseLand.TotalNums = 0;
            item.NoUseLand.TotalArea = 0.0;
            item.NoUseLand.LandTypeMap = new HashMap<>();
            for (int i = 0; i < landresultResult.getResultList().size(); ++i) {
                LandUseStatusItem landUseStatusItem = landresultResult.getResultList().get(i);
                // 农用地汇总
                for (Map.Entry<String, LandType> entry : landUseStatusItem.FarmLand.LandTypeMap.entrySet()) {
                    String key = entry.getKey();
                    LandType landType = entry.getValue();
                    if (key != null && !key.isEmpty()) {
                        item.FarmLand.TotalNums = item.FarmLand.TotalNums + landType.TotalNums;
                        item.FarmLand.TotalArea = item.FarmLand.TotalArea + landType.TotalAreas;
                        if (item.FarmLand.LandTypeMap.isEmpty()) {
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = landType.TotalNums;
                            landTypeItem.TotalAreas = landType.TotalAreas;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = landType.LandTypeName;
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.addAll(landType.Graphic);
                            item.FarmLand.LandTypeMap.put(landType.LandTypeName, landTypeItem);

                        } else if (item.FarmLand.LandTypeMap.containsKey(landType.LandTypeName)) {
                            try {
                                item.FarmLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalNums = item.FarmLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalNums + landType.TotalNums;
                                item.FarmLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalAreas = item.FarmLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalAreas + landType.TotalAreas;
                                item.FarmLand.LandTypeMap.get(landType.LandTypeName).Graphic.addAll(landType.Graphic);
                            } catch (Exception e) {
                                String ee = e.toString();
                            }
                        } else {
                            // 已有十二类其他数据而没有该类时处理
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = landType.TotalNums;
                            landTypeItem.TotalAreas = landType.TotalAreas;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = landType.LandTypeName;
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.addAll(landType.Graphic);
                            item.FarmLand.LandTypeMap.put(landType.LandTypeName, landTypeItem);
                        }

                    }
                }
                // 建设用地汇总
                for (Map.Entry<String, LandType> entry : landUseStatusItem.BuildLand.LandTypeMap.entrySet()) {
                    String key = entry.getKey();
                    LandType landType = entry.getValue();
                    if (key != null && !key.isEmpty()) {
                        item.BuildLand.TotalNums = item.BuildLand.TotalNums + landType.TotalNums;
                        item.BuildLand.TotalArea = item.BuildLand.TotalArea + landType.TotalAreas;
                        if (item.BuildLand.LandTypeMap.isEmpty()) {
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = landType.TotalNums;
                            landTypeItem.TotalAreas = landType.TotalAreas;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = landType.LandTypeName;
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.addAll(landType.Graphic);
                            item.BuildLand.LandTypeMap.put(landType.LandTypeName, landTypeItem);

                        } else if (item.BuildLand.LandTypeMap.containsKey(landType.LandTypeName)) {
                            try {
                                item.BuildLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalNums = item.BuildLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalNums + landType.TotalNums;
                                item.BuildLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalAreas = item.BuildLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalAreas + landType.TotalAreas;
                                item.BuildLand.LandTypeMap.get(landType.LandTypeName).Graphic.addAll(landType.Graphic);
                            } catch (Exception e) {
                                String ee = e.toString();
                            }
                        } else {
                            // 已有十二类其他数据而没有该类时处理
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = landType.TotalNums;
                            landTypeItem.TotalAreas = landType.TotalAreas;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = landType.LandTypeName;
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.addAll(landType.Graphic);
                            item.BuildLand.LandTypeMap.put(landType.LandTypeName, landTypeItem);
                        }

                    }
                }
                // 未利用地汇总
                for (Map.Entry<String, LandType> entry : landUseStatusItem.NoUseLand.LandTypeMap.entrySet()) {
                    String key = entry.getKey();
                    LandType landType = entry.getValue();
                    if (key != null && !key.isEmpty()) {
                        item.NoUseLand.TotalNums = item.NoUseLand.TotalNums + landType.TotalNums;
                        item.NoUseLand.TotalArea = item.NoUseLand.TotalArea + landType.TotalAreas;
                        if (item.NoUseLand.LandTypeMap.isEmpty()) {
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = landType.TotalNums;
                            landTypeItem.TotalAreas = landType.TotalAreas;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = landType.LandTypeName;
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.addAll(landType.Graphic);
                            item.NoUseLand.LandTypeMap.put(landType.LandTypeName, landTypeItem);

                        } else if (item.NoUseLand.LandTypeMap.containsKey(landType.LandTypeName)) {
                            try {
                                item.NoUseLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalNums = item.NoUseLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalNums + landType.TotalNums;
                                item.NoUseLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalAreas = item.NoUseLand.LandTypeMap
                                        .get(landType.LandTypeName).TotalAreas + landType.TotalAreas;
                                item.NoUseLand.LandTypeMap.get(landType.LandTypeName).Graphic.addAll(landType.Graphic);
                            } catch (Exception e) {
                                String ee = e.toString();
                            }
                        } else {
                            // 已有十二类其他数据而没有该类时处理
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = landType.TotalNums;
                            landTypeItem.TotalAreas = landType.TotalAreas;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = landType.LandTypeName;
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.addAll(landType.Graphic);
                            item.NoUseLand.LandTypeMap.put(landType.LandTypeName, landTypeItem);
                        }

                    }
                }
            }
            return item;
        }

        private void InitLandTypeExcel(LandUseStatusAnalysisResult landresult) {
            // TODO Auto-generated method stub
            LandUseStatusAnalysisResult land = landresult;
            int nums = 0;
            double areas = 0;
            tbSummaryTitle.setText("用地类型汇总(单位:亩)");
            tbMoreInfoTitle.setText("地类名称汇总(单位:亩)");
            tvFarmLandSum.setText(land.FarmNums.toString());
            tvFarmLandArea.setText(String.format("%.2f", land.FarmArea));
            tvBuildLandSum.setText(land.BuildNums.toString());
            tvBuildLandArea.setText(String.format("%.2f", land.BuildArea));
            tvNoUseLandSum.setText(land.NoUseNums.toString());
            tvNoUseLandArea.setText(String.format("%.2f", land.NoUseArea));
            nums = land.FarmNums + land.BuildNums + land.NoUseNums;
            areas = land.FarmArea + land.BuildArea + land.NoUseArea;
            tv_sum.setText(String.valueOf(nums));
            tv_area.setText(String.format("%.2f", areas));

        }

    };

    /**
     * 程序入口
     *
     * @param savedInstanceState
     */
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initMapView();
        initGeodatabase();
        setListeners();
        initGeodatabases();

    }

    /**
     * 初始化控件和加载底图
     */
    private void initMapView() {
        mMapView = (MapView) findViewById(R.id.mapview);
        mMapView.setMapBackground(0xFAFAFA, 0xffffff, 0.0f, 0.0f);//地图背景
        String url = Environment.getExternalStorageDirectory().toString() + "/datas/新安县410323.tpk";
        ArcGISLocalTiledLayer layer = new ArcGISLocalTiledLayer(url);
        mMapView.addLayer(layer);

        mPoints = new ArrayList<Point>();
        mMarkerSymbol = new SimpleMarkerSymbol(Color.RED, 10, SimpleMarkerSymbol.STYLE.CIRCLE);
        messurePolygon = new Polygon();// 初始化一个面
        messureLineSymbol = new SimpleLineSymbol(Color.BLUE, 3);// 初始化线的样式
        messureMarkerSymbol = new SimpleMarkerSymbol(Color.RED, 10, SimpleMarkerSymbol.STYLE.CIRCLE);// 初始化测量时点的样式
        messureLine = new Line();// 初始化测距线段
        messureLayer = new GraphicsLayer();// 初始化测量图层
        messurePolyline = new Polyline();// 初始化测距线段组
        pAnalysistSymbol = new SimpleLineSymbol(Color.RED, 3);
        messureFillSymbol = new SimpleFillSymbol(Color.argb(100, 225, 225, 0));// 初始化测量时面的样式
        messureFillSymbol.setOutline(new SimpleLineSymbol(Color.BLACK, 2));// 面积的边框颜色
        messureFillSymbol_red = new SimpleFillSymbol(Color.argb(100, 225, 0, 0));
        messureFillSymbol_red.setOutline(new SimpleLineSymbol(Color.BLACK, 2));
        messureFillSymbol_blue = new SimpleFillSymbol(Color.argb(100, 0, 0, 225));
        messureFillSymbol_blue.setOutline(new SimpleLineSymbol(Color.BLACK, 2));
        messureFillSymbol_green = new SimpleFillSymbol(Color.argb(100, 0, 225, 0));
        messureFillSymbol_green.setOutline(new SimpleLineSymbol(Color.BLACK, 2));
        pointAnalysistAllGraphicsLayer = new GraphicsLayer();
        pointAnalysistOneGraphicsLayer = new GraphicsLayer();
        mMapView.addLayer(messureLayer);// 添加测量要素图层
        mMapView.addLayer(pointAnalysistAllGraphicsLayer);
        mMapView.addLayer(pointAnalysistOneGraphicsLayer);
        Landresult = new LandUseStatusAnalysisResult();
        pointAnalysistGraphics = new ArrayList<>();
        mMarkerSymbol = new SimpleMarkerSymbol(Color.RED, 10, SimpleMarkerSymbol.STYLE.CIRCLE);

        mPoints = new ArrayList<Point>();
        mySlidingLayer = (SlidingLayer) findViewById(R.id.sliding_layers);
        mySlidingLayer.setStickTo(SlidingLayer.STICK_TO_LEFT);
        lv = (ListView) findViewById(R.id.lv_tjfx);
        tv_zmj = (TextView) findViewById(R.id.tv_zmj);
        tv_nmj = (TextView) findViewById(R.id.tv_nmj);
        tv_controltitle = (TextView) findViewById(R.id.tv_controltitle);
        tv_jmj = (TextView) findViewById(R.id.tv_jmj);
        tv_wmj = (TextView) findViewById(R.id.tv_wmj);

        rbtSummaryInfo = (RadioButton) findViewById(R.id.rtn_summary_info);
        rbtMoreInfo = (RadioButton) findViewById(R.id.rtn_more_info);
        rbt_xzqh = (RadioButton) findViewById(R.id.rtn_xzqh);
        rbt_ydlx = (RadioButton) findViewById(R.id.rtn_ydlx);
        rbt_dlmc = (RadioButton) findViewById(R.id.rtn_dlmc);
        cvTjResult = (LinearLayout) findViewById(R.id.cv_tjfx);
        ll_zj1 = (LinearLayout) findViewById(R.id.ll_zj1);
        ll_zj2 = (LinearLayout) findViewById(R.id.ll_zj2);
        chartTjResult = (PieChartView) findViewById(R.id.chart_tjfx);
        tbSummaryTitle = (TextView) findViewById(R.id.tb_summary_title);
        tbSummary = (TableLayout) findViewById(R.id.tb_summary);
        tvFarmLandSum = (TextView) findViewById(R.id.tv_farmland_sum);
        tvFarmLandArea = (TextView) findViewById(R.id.tv_farmland_area);
        tvBuildLandSum = (TextView) findViewById(R.id.tv_buildland_sum);
        tvBuildLandArea = (TextView) findViewById(R.id.tv_buildland_area);
        tvNoUseLandSum = (TextView) findViewById(R.id.tv_nouseland_sum);
        tvNoUseLandArea = (TextView) findViewById(R.id.tv_nouseland_area);
        tv_sum = (TextView) findViewById(R.id.tv_sum);
        tv_area = (TextView) findViewById(R.id.tv_area);
        tbMoreInfoTitle = (TextView) findViewById(R.id.tb_moreinfo_title);
        tbMoreInfo = (TableLayout) findViewById(R.id.tb_moreinfo);
        tbPlanInfoTitle = (TextView) findViewById(R.id.tb_plan_info_title);
        tbPlanInfo = (TableLayout) findViewById(R.id.tb_plan_info);
        tbControlTitle = (TextView) findViewById(R.id.tb_control_title);
        tbControl = (TableLayout) findViewById(R.id.tb_control);
        tbControlTitle2 = (TextView) findViewById(R.id.tb_control_title2);
        tbControl2 = (TableLayout) findViewById(R.id.tb_control2);
        tvdlmc = (TextView) findViewById(R.id.tv_dlmc);
        tvdllb = (TextView) findViewById(R.id.tv_dllb);
    }

    /**
     * 加载适量数据并生产对象
     */

    private void initGeodatabase() {
        String url = Environment.getExternalStorageDirectory().toString() + "/datas/data.geodatabase";
        Geodatabase localGdb = null;
        try {
            localGdb = new Geodatabase(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (localGdb != null) {
            for (GeodatabaseFeatureTable gdbFeatureTable : localGdb.getGeodatabaseTables()) {
                if (gdbFeatureTable.hasGeometry()) {
                    if (gdbFeatureTable.getTableName().equals("土地利用现状"))
                        dataFeatureLayer = new FeatureLayer(gdbFeatureTable);

                    // mMapView.addLayer(dataFeatureLayer);
                }
            }

        }
    }


    private void initGeodatabases() {
        Gson gson = new Gson();
        final String url = Environment.getExternalStorageDirectory().toString() + "/datas/410323新安县.geodatabase";
        Geodatabase localGdb = null;
        try {
            localGdb = new Geodatabase(url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (localGdb != null) {
            for (final GeodatabaseFeatureTable gdbFeatureTable : localGdb.getGeodatabaseTables()) {
                final List<Map<String, Object>> vLayer = new ArrayList<Map<String, Object>>();
                if (gdbFeatureTable.hasGeometry()) {
                    //捕获线程池拒绝执行异常
                    try {
                        // 线程放入线程池
                        DEFAULT_TASK_EXECUTOR.execute(new Runnable() {
                            @Override
                            public void run() {
                                dataFeatureLayer = new FeatureLayer(gdbFeatureTable);
                                final FeatureTable rs = dataFeatureLayer.getFeatureTable();
                                final Gson gson = new Gson();
                                //   String cJSON=gson.toJson(rs);
                                //Log.e(rs.getTableName(),cJSON);
                                if (rs.getTableName().equals("自然与历史文化保护区")) {
                                    QueryParameters query = new QueryParameters();
                                    query.setOutFields(new String[]{"*"});
                                    query.setGeometry(null);
                                    rs.queryFeatures(query, new CallbackListener<FeatureResult>() {
                                        @Override
                                        public void onCallback(FeatureResult featureResul) {
                                            for (Object resultItem : featureResul) {
                                                Feature feature = (Feature) resultItem;
                                                if (feature != null) {
                                                Map<String, Object> vf = new HashMap<String, Object>();
                                                vf = feature.getAttributes();
                                                String json = GeometryEngine.geometryToJson(SpatialReference.create(SpatialReference.WKID_WGS84), feature.getGeometry());
                                            try {
                                                JSONObject vJson = new JSONObject(json);
                                                String jsonRing = vJson.getString("rings");
                                                vf.put("shape", jsonRing);
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                            vLayer.add(vf);
                                        }


                                            }
                                            String jsonstring = gson.toJson(vLayer);
                                    TxtToFile.writeTxtToFile(jsonstring, Environment.getExternalStorageDirectory().toString() + "/datas", rs.getTableName() + ".txt");

                                        }

                                        @Override
                                        public void onError(Throwable throwable) {

                                        }
                                    });
//                                    long s = rs.getNumberOfFeatures();
//                                    for (long i = 0; i < s; i++) {
//                                        Feature ftr = null;
//                                        try {
//                                            ftr = rs.getFeature(i);
//                                            //    Log.e("getAttributes",ftr.getAttributes().toString());
//                                            //ftr.getAttributes().toString();
//                                        } catch (TableException e) {
//                                            e.printStackTrace();
//                                        }
//                                        if (ftr != null) {
//                                            Map<String, Object> vf = new HashMap<String, Object>();
//                                            vf = ftr.getAttributes();
//                                            String json = GeometryEngine.geometryToJson(SpatialReference.create(SpatialReference.WKID_WGS84), ftr.getGeometry());
//                                            try {
//                                                JSONObject vJson = new JSONObject(json);
//                                                String jsonRing = vJson.getString("rings");
//                                                vf.put("shape", jsonRing);
//                                            } catch (JSONException e) {
//                                                e.printStackTrace();
//                                            }
//                                            vLayer.add(vf);
//                                        }
//                                    }
//                                    String jsonstring = gson.toJson(vLayer);
//                                    TxtToFile.writeTxtToFile(jsonstring, Environment.getExternalStorageDirectory().toString() + "/datas", rs.getTableName() + ".txt");
                                }


                            }


                        });
                    } catch (RejectedExecutionException e) {
                        e.printStackTrace();
                    }

//                        Feature ftr = rs.getFeature(1);
//                        Polygon v= (Polygon) ftr.getGeometry();
//                        String json = GeometryEngine.geometryToJson(SpatialReference.create(SpatialReference.WKID_WGS84), ftr.getGeometry());
//                        byte[] vByte = GeometryEngine.geometryToEsriShape(ftr.getGeometry());
//                        Object vData =ftr.getAttributes();
//                        Log.e("json",  ftr.getAttributes() + "-----------------" + json)

                    //   mMapView.addLayer(dataFeatureLayer);
                }
            }
        }
    }

    private void setListeners() {
        rbtSummaryInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lv.setVisibility(View.GONE);
                ll_zj1.setVisibility(View.GONE);
                ll_zj2.setVisibility(View.GONE);
                rbt_xzqh.setVisibility(View.VISIBLE);
                rbt_dlmc.setVisibility(View.VISIBLE);
                rbt_ydlx.setVisibility(View.VISIBLE);
                cvTjResult.setVisibility(View.VISIBLE);
            }
        });

        rbtMoreInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ll_zj1.setVisibility(View.VISIBLE);
                ll_zj2.setVisibility(View.VISIBLE);
                lv.setVisibility(View.VISIBLE);
                rbt_xzqh.setVisibility(View.GONE);
                rbt_dlmc.setVisibility(View.GONE);
                rbt_ydlx.setVisibility(View.GONE);
                cvTjResult.setVisibility(View.GONE);
            }
        });
        chartTjResult.setOnValueTouchListener(new PieChartOnValueSelectListener() {
            @Override
            public void onValueSelected(int arcIndex, SliceValue value) {
                pointAnalysistOneGraphicsLayer.removeAll();
                String strLabel = "";
                char[] labelCharArr = value.getLabelAsChars();
                for (int i = 0; i < labelCharArr.length; i++) {
                    strLabel += labelCharArr[i];
                }
                for (Graphic graphic : LandPer.get(strLabel)) {
                    pointAnalysistOneGraphicsLayer.addGraphic(graphic);
                }
            }

            @Override
            public void onValueDeselected() {

            }
        });
        mMapView.setOnSingleTapListener(new OnSingleTapListener() {
            @Override
            public void onSingleTap(float v, float v1) {
                Point mPoint = mMapView.toMapPoint(v, v1);// 选择点
                mPoints.add(mPoint);// 选择点加入点的集合
                Graphic messurePoint = new Graphic(mPoint, mMarkerSymbol);// 点的要素初始化
                messureLayer.addGraphic(messurePoint);// 点的要素添加到图层
                if (mPoints.size() == 1) {
                    messurePolygon.startPath(mPoints.get(0));// 设置面的初始点
                }
                if (mPoints.size() > 1) {
                    messureLayer.removeAll();
                    messurePolyline.setEmpty();
                    messurePolygon.lineTo(mPoint);// 连接到当前点击的点
                    messurePolygon.lineTo(mPoints.get(0));// 连接到初始点
                    for (int i = 0; i < mPoints.size() - 1; i++) {
                        messureLine.setStart(mPoints.get(i));
                        messureLine.setEnd(mPoints.get(i + 1));
                        messurePolyline.addSegment(messureLine, true);
                        messureLayer.addGraphic(new Graphic(mPoints.get(i), messureMarkerSymbol));
                    }
                    messureLayer.addGraphic(new Graphic(mPoints.get(mPoints.size() - 1), messureMarkerSymbol));
                    messureLine.setStart(mPoint);
                    messureLine.setEnd(mPoints.get(0));
                    messurePolyline.addSegment(messureLine, true);
                    messureLineGraphic = new Graphic(messurePolyline, messureLineSymbol);
                    messureAreaGraphic = new Graphic(messurePolygon, messureFillSymbol);// 初始化面的要素
                    messureLayer.addGraphic(messureAreaGraphic);// 将面的要素添加到图层
                    messureLayer.addGraphic(messureLineGraphic);
                    messurePolygon.startPath(mPoint);// 将当前点设为初始点
                }
            }
        });

        /**
         * 长按分析
         */
        mMapView.setOnLongPressListener(new OnLongPressListener() {
            @Override
            public boolean onLongPress(float v, float v1) {
                try {
                    QueryParameters query = new QueryParameters();
                    query.setOutFields(new String[]{"*"});// 设置返回字段的数组
                    query.setGeometry(messurePolygon);// 设置空间几何对象
                    if (dataFeatureLayer == null) {
                        return false;
                    } else {
                        FeatureTable mTable = dataFeatureLayer.getFeatureTable();
                        mTable.queryFeatures(query, new CallbackListener<FeatureResult>() {
                            @Override
                            public void onCallback(FeatureResult featureResul) {
                                //解析分析结果
                                Landresult = getLandUseStatusAnalysisResultByPoints(featureResul);
                                Message msg = new Message();
                                msg.what = ANALYSIS;
                                handler.sendMessage(msg);
                            }

                            @Override
                            public void onError(Throwable throwable) {

                            }
                        });

                    }
                } catch (Exception e) {
                    Toast toast = Toast.makeText(MainActivity.this, "查寻异常", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
                return false;
            }
        });
    }

    public LandUseStatusAnalysisResult getLandUseStatusAnalysisResultByPoints(FeatureResult featureResult) {
        LandUseStatusAnalysisResult resut = new LandUseStatusAnalysisResult();
        // 先将最小粒度的地块的面积、graphic、和数量
        Integer totalNums = 0; // 总计地块数的计算
        Double totalArea = 0.0; // 总计面积数的计算
        Integer farmNums = 0;
        Double farmArea = 0.0;
        Integer buildNums = 0;
        Double buildArea = 0.0;
        Integer nouseNums = 0;
        Double nouseArea = 0.0;
        List<Graphic> graphicList = new ArrayList<>();
        List<Graphic> F = new ArrayList<>();
        List<Graphic> B = new ArrayList<>();
        List<Graphic> N = new ArrayList<>();
        List<LandUseStatusItem> resultList = new ArrayList<>();

        // 以权属单位分组计算
        Map<String, List<PAnalysistItemInfo>> groupMap = getGroupMapByGS(featureResult, "QSDWMC");
        for (Map.Entry<String, List<PAnalysistItemInfo>> entry : groupMap.entrySet()) {
            String qsdwmc = entry.getKey();
            List<PAnalysistItemInfo> qsItemList = entry.getValue();
            LandUseStatusItem landUseStatusItem = getLandUseStatusItem(qsdwmc, qsItemList);// 归类计算
            // landUseStatusItem = getTextOperate(landUseStatusItem);//拼接文本
            totalNums = totalNums + landUseStatusItem.FarmLand.TotalNums + landUseStatusItem.BuildLand.TotalNums
                    + landUseStatusItem.NoUseLand.TotalNums;
            totalArea = totalArea + landUseStatusItem.FarmLand.TotalArea + landUseStatusItem.BuildLand.TotalArea
                    + landUseStatusItem.NoUseLand.TotalArea;
            farmNums = farmNums + landUseStatusItem.FarmLand.TotalNums;
            farmArea = farmArea + landUseStatusItem.FarmLand.TotalArea;
            buildNums = buildNums + landUseStatusItem.BuildLand.TotalNums;
            buildArea = buildArea + landUseStatusItem.BuildLand.TotalArea;
            nouseNums = nouseNums + landUseStatusItem.NoUseLand.TotalNums;
            nouseArea = nouseArea + landUseStatusItem.NoUseLand.TotalArea;
            F.addAll(landUseStatusItem.FarmLand.GraphicList);
            B.addAll(landUseStatusItem.BuildLand.GraphicList);
            N.addAll(landUseStatusItem.NoUseLand.GraphicList);
            resultList.add(landUseStatusItem);
        }
        // 计算总计数据
        resut.TotalNums = totalNums;
        resut.TotalArea = totalArea;
        resut.FarmNums = farmNums;
        resut.FarmArea = farmArea;
        resut.BuildNums = buildNums;
        resut.BuildArea = buildArea;
        resut.NoUseNums = nouseNums;
        resut.NoUseArea = nouseArea;
        resut.BuildGraphic = B;
        resut.FarmGraphic = F;
        resut.NoUseGraphic = N;
        resut.GraphicList = graphicList;
        resut.ResultList = resultList;
        return resut;
    }

    /**
     * 分析数据
     *
     * @param featureResult
     * @param qsFieldName
     * @return
     */
    private Map<String, List<PAnalysistItemInfo>> getGroupMapByGS(FeatureResult featureResult, String qsFieldName) {
        Map<String, List<PAnalysistItemInfo>> groupMap = new HashMap<>();
        pAnalysistItemInfoList = new ArrayList();
        try {
            if (featureResult != null && featureResult.featureCount() > 0) {
                for (Object resultItem : featureResult) {
                    Feature feature = (Feature) resultItem;// 遍历出一个结果
                    if (feature instanceof Feature) {
                        Feature searchFeature = (Feature) feature;
                        Map<String, Object> mQuerryString = feature.getAttributes();
                        Log.e("feature", feature.toString());
                        Log.e("mQuerryString", mQuerryString.toString());
                        Geometry mGeometry = GeometryEngine.intersect(searchFeature.getGeometry(), messurePolygon,
                                mMapView.getSpatialReference());
                        PAnalysistItemInfo itemInfoTemp = new PAnalysistItemInfo();
                        mGeometry = GeometryEngine.geodesicDensifyGeometry(mGeometry, mMapView.getSpatialReference());
                        String dltype = getLandType("DLBM", mQuerryString).toString();
                        if (dltype.equals("")) {
                            continue;
                        }
                        // 储存属性信息
                        itemInfoTemp.setDlName(mQuerryString.get("DLMC").toString());
                        String area1 = String.format("%.2f",
                                Double.valueOf(
                                        GeometryEngine.geodesicArea(mGeometry, mMapView.getSpatialReference(), null))
                                        * 0.0015);
                        itemInfoTemp.setDlArea(area1);
                        itemInfoTemp.setDlType(dltype);

                        // 储存图形信息
                        Graphic mFeatureResultGraphic = new Graphic(mGeometry, pAnalysistSymbol);
                        pointAnalysistGraphics.add(mFeatureResultGraphic);

                        if (dltype.equals("农用地")) {
                            messureAreaGraphic = new Graphic(mGeometry, messureFillSymbol_green);
                            pointAnalysistAllGraphicsLayer.addGraphic(messureAreaGraphic);
                        } else if (dltype.equals("建设用地")) {
                            messureAreaGraphic = new Graphic(mGeometry, messureFillSymbol_red);
                            pointAnalysistAllGraphicsLayer.addGraphic(messureAreaGraphic);
                        } else if (dltype.equals("未利用地")) {
                            messureAreaGraphic = new Graphic(mGeometry, messureFillSymbol_blue);
                            pointAnalysistAllGraphicsLayer.addGraphic(messureAreaGraphic);
                        }
                        itemInfoTemp.setGraphic(mFeatureResultGraphic);

                        String code = mQuerryString.get(qsFieldName).toString();

                        if (groupMap.isEmpty() || (!groupMap.containsKey(code))) {
                            List<PAnalysistItemInfo> list = new ArrayList<>();
                            groupMap.put(code, list);
                        }
                        groupMap.get(code).add(itemInfoTemp);

                        pAnalysistItemInfoList.add(itemInfoTemp);
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return groupMap;
    }

    private String getLandType(String keyField, Map<String, Object> mQuerryString) {
        String code = mQuerryString.get(keyField).toString();
        String landType = "";
        if (code.equals("011") || code.equals("012") || code.equals("013")// 十二类之耕地01
                || code.equals("021") || code.equals("022") || code.equals("023")// 十二类之园地02
                || code.equals("031") || code.equals("032") || code.equals("033")// 十二类之林地03
                || code.equals("041") || code.equals("042")// 十二类之草地04
                || code.equals("104")// 十二类之水域及水利设施用地11
                || code.equals("114") || code.equals("117") || code.equals("122") || code.equals("123")) {
            landType = "农用地";
        } else if (code.equals("051") || code.equals("052") || code.equals("053") || code.equals("054")
                || code.equals("061") || code.equals("062") || code.equals("063") || code.equals("071")
                || code.equals("072") || code.equals("081") || code.equals("082") || code.equals("083")
                || code.equals("084") || code.equals("085") || code.equals("086") || code.equals("087")
                || code.equals("088") || code.equals("091") || code.equals("092") || code.equals("093")
                || code.equals("094") || code.equals("095") || code.equals("101") || code.equals("102")
                || code.equals("103") || code.equals("104") || code.equals("105") || code.equals("106")
                || code.equals("107") || code.equals("113") || code.equals("118") || code.equals("121")
                || code.equals("201") || code.equals("202") || code.equals("203") || code.equals("204")
                || code.equals("205")) {
            landType = "建设用地";
        } else if (code.equals("043") || code.equals("111") || code.equals("112") || code.equals("115")
                || code.equals("116") || code.equals("119") || code.equals("124") || code.equals("125")
                || code.equals("126") || code.equals("127")) {
            landType = "未利用地";
        }
        return landType;
    }

    private LandUseStatusItem getLandUseStatusItem(String qsName, List<PAnalysistItemInfo> paList) {
        LandUseStatusItem item = new LandUseStatusItem();
        item.AdmName = qsName;
        // 初始化
        item.FarmLand = new FarmLand();
        item.FarmLand.TotalNums = 0;
        item.FarmLand.TotalArea = 0.0;
        item.FarmLand.LandTypeMap = new HashMap<>();
        item.FarmLand.GraphicList = new ArrayList<Graphic>();
        item.BuildLand = new BuildLand();
        item.BuildLand.TotalNums = 0;
        item.BuildLand.TotalArea = 0.0;
        item.BuildLand.LandTypeMap = new HashMap<>();
        item.BuildLand.GraphicList = new ArrayList<Graphic>();
        item.NoUseLand = new NoUseLand();
        item.NoUseLand.TotalNums = 0;
        item.NoUseLand.TotalArea = 0.0;
        item.NoUseLand.LandTypeMap = new HashMap<>();
        item.NoUseLand.GraphicList = new ArrayList<Graphic>();
        item.GraphicList = new ArrayList<Graphic>();
        // 归类计算
        if (paList != null && !paList.isEmpty()) {
            for (PAnalysistItemInfo paItem : paList) {
                Double area = 0.0;
                Graphic graphic = null;
                try {
                    area = Double.parseDouble(paItem.getDlArea());
                    graphic = paItem.getGraphic();
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
                item.GraphicList.add(graphic);
                if (paItem.getDlType().equals("农用地")) {
                    item.FarmLand.TotalNums = item.FarmLand.TotalNums + 1;
                    item.FarmLand.TotalArea = item.FarmLand.TotalArea + area;
                    item.FarmLand.GraphicList.add(graphic);
                    if (item.FarmLand.LandTypeMap.isEmpty()) {
                        // 十二类无数据时处理
                        LandType landTypeItem = new LandType();
                        landTypeItem.TotalNums = 1;
                        landTypeItem.TotalAreas = area;
                        landTypeItem.LandTypeCode = "";
                        landTypeItem.LandTypeName = paItem.getDlName();
                        landTypeItem.Graphic = new ArrayList<Graphic>();
                        landTypeItem.Graphic.add(graphic);
                        item.FarmLand.LandTypeMap.put(paItem.getDlName(), landTypeItem);
                    } else {
                        if (item.FarmLand.LandTypeMap.containsKey(paItem.getDlName())) {
                            // 存在该类数据时处理
                            if (item.FarmLand.LandTypeMap.get(paItem.getDlName()) != null) {
                                try {
                                    item.FarmLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalNums = item.FarmLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalNums + 1;
                                    item.FarmLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalAreas = item.FarmLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalAreas + area;
                                    item.FarmLand.LandTypeMap.get(paItem.getDlName()).Graphic.add(graphic);
                                } catch (Exception e) {
                                    String ee = e.toString();
                                }
                            }

                        } else {
                            // 已有十二类其他数据而没有该类时处理
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = 1;
                            landTypeItem.TotalAreas = area;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = paItem.getDlName();
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.add(graphic);
                            item.FarmLand.LandTypeMap.put(paItem.getDlName(), landTypeItem);
                        }
                    }
                } else if (paItem.getDlType().equals("建设用地")) {
                    item.BuildLand.TotalNums = item.BuildLand.TotalNums + 1;
                    item.BuildLand.TotalArea = item.BuildLand.TotalArea + area;
                    item.BuildLand.GraphicList.add(graphic);
                    if (item.BuildLand.LandTypeMap.isEmpty()) {
                        // 十二类无数据时处理
                        LandType landTypeItem = new LandType();
                        landTypeItem.TotalNums = 1;
                        landTypeItem.TotalAreas = area;
                        landTypeItem.LandTypeCode = "";
                        landTypeItem.LandTypeName = paItem.getDlName();
                        landTypeItem.Graphic = new ArrayList<Graphic>();
                        landTypeItem.Graphic.add(graphic);
                        item.BuildLand.LandTypeMap.put(paItem.getDlName(), landTypeItem);
                    } else {
                        if (item.BuildLand.LandTypeMap.containsKey(paItem.getDlName())) {
                            // 存在该类数据时处理
                            if (item.BuildLand.LandTypeMap.get(paItem.getDlName()) != null) {
                                try {
                                    item.BuildLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalNums = item.BuildLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalNums + 1;
                                    item.BuildLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalAreas = item.BuildLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalAreas + area;
                                    item.BuildLand.LandTypeMap.get(paItem.getDlName()).Graphic.add(graphic);
                                } catch (Exception e) {
                                    String ee = e.toString();
                                }
                            }

                        } else {
                            // 已有十二类其他数据而没有该类时处理
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = 1;
                            landTypeItem.TotalAreas = area;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = paItem.getDlName();
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.add(graphic);
                            item.BuildLand.LandTypeMap.put(paItem.getDlName(), landTypeItem);
                        }
                    }
                } else if (paItem.getDlType().equals("未利用地")) {
                    item.NoUseLand.TotalNums = item.NoUseLand.TotalNums + 1;
                    item.NoUseLand.TotalArea = item.NoUseLand.TotalArea + area;
                    item.NoUseLand.GraphicList.add(graphic);
                    if (item.NoUseLand.LandTypeMap.isEmpty()) {
                        // 十二类无数据时处理
                        LandType landTypeItem = new LandType();
                        landTypeItem.TotalNums = 1;
                        landTypeItem.TotalAreas = area;
                        landTypeItem.LandTypeCode = "";
                        landTypeItem.LandTypeName = paItem.getDlName();
                        landTypeItem.Graphic = new ArrayList<Graphic>();
                        landTypeItem.Graphic.add(graphic);
                        item.NoUseLand.LandTypeMap.put(paItem.getDlName(), landTypeItem);
                    } else {
                        if (item.NoUseLand.LandTypeMap.containsKey(paItem.getDlName())) {
                            // 存在该类数据时处理
                            if (item.NoUseLand.LandTypeMap.get(paItem.getDlName()) != null) {
                                try {
                                    item.NoUseLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalNums = item.NoUseLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalNums + 1;
                                    item.NoUseLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalAreas = item.NoUseLand.LandTypeMap
                                            .get(paItem.getDlName()).TotalAreas + area;
                                    item.NoUseLand.LandTypeMap.get(paItem.getDlName()).Graphic.add(graphic);
                                } catch (Exception e) {
                                    String ee = e.toString();
                                }
                            }

                        } else {
                            // 已有十二类其他数据而没有该类时处理
                            LandType landTypeItem = new LandType();
                            landTypeItem.TotalNums = 1;
                            landTypeItem.TotalAreas = area;
                            landTypeItem.LandTypeCode = "";
                            landTypeItem.LandTypeName = paItem.getDlName();
                            landTypeItem.Graphic = new ArrayList<Graphic>();
                            landTypeItem.Graphic.add(graphic);
                            item.NoUseLand.LandTypeMap.put(paItem.getDlName(), landTypeItem);
                        }
                    }

                }
            }
        }
        return item;
    }

    private void zoomToArea(ArrayList<Point> mDataList) {
        double p_right, p_top, p_left, p_bottom;
        if (mDataList.size() != 0) {
            // 计算出采集点的最小外切矩阵，显示整个采集区域
            p_right = mDataList.get(0).getX();
            p_top = mDataList.get(0).getY();
            p_left = mDataList.get(0).getX();
            p_bottom = mDataList.get(0).getY();
            for (int i = 1; i < mDataList.size(); i++) {
                double m = mDataList.get(i).getX();
                double n = mDataList.get(i).getY();
                if (p_right < m) { // 外切矩阵X轴最大坐标
                    p_right = m;
                }
                if (p_left > m) { // 外切矩阵X轴最小坐标
                    p_left = m;
                }
                if (p_top < n) { // 外切矩阵Y轴最大坐标
                    p_top = n;
                }
                if (p_bottom > n) { // 外切矩阵Y轴最小坐标
                    p_bottom = n;
                }
                // 设置边框显示范围
                Envelope initialExtent = new Envelope(p_left - 1000, p_bottom - 1000, p_right + 1000, p_top + 1000);
                mMapView.setExtent(initialExtent);
            }
        }
    }
}

